import typescript from 'rollup-plugin-typescript2'
// import clear from 'rollup-plugin-clear'
import dts from 'rollup-plugin-dts'
import { readFileSync } from 'fs'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import * as path from 'path'

const packageDir = new URL(process.env.TARGET, import.meta.url)
const dirname = new URL('.', import.meta.url).pathname

const resolve = p => path.resolve(packageDir.pathname, p)

const pkg = JSON.parse(readFileSync(resolve('./package.json')))

const input = resolve('./src/index.ts')

const external = [
  ...Object.keys(pkg.dependencies || {}),
  ...Object.keys(pkg.devDependencies || {}),
  ...Object.keys(pkg.peerDependencies || {})
]
// tsconfig: new URL('tsconfig.json', import.meta.url)
const plugins = [
  // clear({
  //   targets: [resolve('dist')]
  // }),

  typescript({
    tsconfig: path.resolve(dirname, './tsconfig.json'),
    tsconfigOverride: {
      compilerOptions: {
        declaration: false // 重置ts 输出 主要针对.d.ts文件   这个开启会把所有的.d.ts生成到当前文件下
      }
    },
    clean: true // 禁用缓存并执行干净生成
  }),
  nodeResolve()
]

export default [
  {
    // 生成 .d.ts 类型声明文件
    input,
    output: { file: resolve(pkg.types), format: 'es' },
    plugins: [dts()]
  },
  {
    input,
    output: { file: resolve(pkg.module), format: 'esm', sourcemap: false },
    plugins,
    external
  },
  {
    input,
    output: { file: resolve(pkg.main), format: 'cjs', sourcemap: false },
    plugins,
    external
  }
]
